<template>  
  <div class="fulltable">  
    <div class="full">   
      <div class="add">  
        <button class="button" @click="showAddModal = true">➕新增</button>  
        <button class="button" @click="showAddStandardModal = true" style="margin-left:20px" v-if="checkUserRole()">➕新增考勤标准</button> 
        <span style="margin-left:20px">注：如有考勤标准则新增标准会覆盖原标准</span>
      </div> 
      <div class="search">  
        <el-input v-model="searchName" placeholder="输入打卡人" @input="filterData" clearable style="margin-right: 10px;width:200px"></el-input>  
        <el-select v-model="selectedType" placeholder="筛选类型" clearable style="margin-right: 10px;width:200px">  
          <el-option label="上班" value="上班"></el-option>  
          <el-option label="下班" value="下班"></el-option>  
        </el-select>  
      </div> 
      <el-table  
        :data="filteredAttendanceData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"  
        :height="tableHeight"  
        border  
        style="width: 100%;border-radius: 10px;">  
        <el-table-column  
          prop="type"  
          label="类型"  
          width="200">  
        </el-table-column>  
        <el-table-column  
          prop="name"  
          label="打卡人"  
          width="200">  
        </el-table-column>  
        <el-table-column  
          prop="time"  
          label="打卡时间"  
          width="300">  
        </el-table-column>  
        <el-table-column  
          prop="notes"  
          label="备注"  
          width="300">  
        </el-table-column>  
        <el-table-column  
          prop="state"  
          label="状态">  
        </el-table-column>  
      </el-table>  
      <div class="paging">
      <el-pagination  
        @size-change="handleSizeChange"  
        @current-change="handleCurrentChange"  
        :current-page="currentPage"  
        :page-sizes="[2,5,10, 20, 40, 60]"  
        :page-size="pageSize"  
        :pager-count="4"
        layout="total, sizes, prev, pager, next, jumper"  
        :total="filteredAttendanceData.length">  
      </el-pagination> 
      </div>
    </div>


<el-dialog title="新增考勤" :visible.sync="showAddModal" width="30%">  
  <el-form :model="newAttendance" label-width="80px" ref="newAttendanceForm">  
    <el-form-item label="类型" prop="type" :rules="[{ required: true, message: '类型不能为空' }]">  
      <el-radio-group v-model="newAttendance.type">  
        <el-radio label="上班"></el-radio>  
        <el-radio label="下班"></el-radio>  
      </el-radio-group>  
    </el-form-item>
      <!-- <el-form-item label="打卡人" prop="name">  
        <el-select v-model="newAttendance.name" filterable placeholder="请选择打卡人" style="width:400px">  
          <el-option v-for="item in userList" :key="item.id" :label="item.realname" :value="item.id"></el-option>  
        </el-select>  
      </el-form-item>  -->
    <el-form-item label="备注" prop="notes">  
      <el-input v-model="newAttendance.notes" type="textarea"></el-input>  
    </el-form-item>  
  </el-form>  
  <span slot="footer" class="dialog-footer">  
    <el-button @click="handleCancelAdd">取 消</el-button>  
    <el-button type="primary" @click="saveNewAttendance">确 定</el-button>  
  </span>  
</el-dialog>

<el-dialog title="新增考勤标准" :visible.sync="showAddStandardModal" width="30%">  
  <el-form :model="newAttendanceStandard" label-width="80px" ref="newAttendanceStandardForm">  
    <el-form-item label="类型" prop="type" :rules="[{ required: true, message: '类型不能为空' }]">  
      <el-radio-group v-model="newAttendanceStandard.type">  
        <el-radio label="上班"></el-radio>  
        <el-radio label="下班"></el-radio>  
      </el-radio-group>  
    </el-form-item>  
    <el-form-item label="标准时间" prop="standardTime" :rules="[{ required: true, message: '标准时间不能为空' }]">  
          <el-time-picker  v-model="newAttendanceStandard.standardTime" :picker-options="{
          selectableRange: '00:00:00 - 23:59:59'
          }" 
    placeholder="选择标准时间" style="width: 100%;">
        </el-time-picker>  
    </el-form-item>
  </el-form>  
  <span slot="footer" class="dialog-footer">  
    <el-button @click="handleCancelAddStandard">取 消</el-button>  
    <el-button type="primary" @click="saveNewAttendanceStandard">确 定</el-button>  
  </span>  
</el-dialog>
  </div>  
</template> 

<script>
import {getAttendanceList,addAttendance,addAttendanceStandard} from '@/api/attendance';
import {getUserList} from '@/api/user';
import {addLog} from '@/api/log';
import { jwtDecode } from 'jwt-decode'; 
export default {
  data(){
    return {
      logItem:{
              mn:'',
              opn:'',
              res:''
      },
      attendanceData:[],
      currentPage: 1,  
      pageSize: 5 ,
      tableHeight: 250,  
      maxTableHeight: 600, // 最大高度 600px  
      minTableHeight: 250,    showAddModal: false, // 新增弹窗的显示状态  
      newAttendance: { // 新增表单的数据  
        type: '',  
        name: '',   
        notes: '' 
      },
      userList:[],
      showAddStandardModal: false, //新增考勤标准的弹窗控制 
      newAttendanceStandard: {  
      type: '',  
      standardTime: ''
    },
    searchName: '',
    selectedType: '',
    }
  },
  computed: {
    filteredAttendanceData() {
      return this.attendanceData.filter(item => {
        const matchesName = item.name.toLowerCase().includes(this.searchName.toLowerCase());
        const matchesType = this.selectedType ? item.type === this.selectedType : true;
        return matchesName && matchesType;
      });
    },
  },
  created(){
    getAttendanceList().then(response=>{
      this.attendanceData = response.data
      this.calculateTableHeight() 
      console.log(response.data)
    }).catch(error =>{
      console.log(error)
      this.tableHeight = this.minTableHeight  
    })

    this.getUsers()
  },
  watch:{
  currentPage() {  
    this.calculateTableHeight()  
  },  
  pageSize() {  
    this.calculateTableHeight()  
  }
  },
  methods:{
    handleSizeChange(val) {  
      this.pageSize = val;  
      this.currentPage = 1;  
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的打卡信息-考勤管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    checkUserRole() {  
    const token = localStorage.getItem('token'); // 从本地存储获取 token  
    if (token) {  
      const decodedToken = jwtDecode(token); // 解码 token  
      return decodedToken.role === 'SUPERMAN'; // 检查角色  
    }  
    return false; // 无 token 返回 false  
  }, 
    handleCurrentChange(val) {  
      this.currentPage = val;  
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-考勤管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
  calculateTableHeight() {  
    // 获取当前页展示的数据量  
    const currentPageData = this.filteredAttendanceData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
    
    // 每行高度为 50px，再加上表头高度 50px，得到总高度  
    let height = (currentPageData.length + 1) * 50  
    console.log(height)
    // 限制高度在 minTableHeight 和 maxTableHeight 之间  
    this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight))  
    console.log(this.tableHeight)
  },
  saveNewAttendance() {  
    this.$refs.newAttendanceForm.validate((valid) => {  
      if (valid) {  
        // 调用后端接口保存新假期  
        addAttendance(this.newAttendance)  
          .then(response => {  
            this.$message.success('考勤成功');  
            this.showAddModal = false;  
            this.logItem.mn = "saveNewAttendance";
            if(this.newAttendance.type==="上班"){
                  this.logItem.opn = "上班打卡";
              }else if(this.newAttendance.type==="下班"){
                this.logItem.opn = "下班打卡";
              }
            this.logItem.res = "true";
            addLog(this.logItem);
            this.resetNewAttendance();  
            window.location.reload()  // 刷新考勤列表  
            
          })  
          .catch(error => {  
            this.logItem.mn = "saveNewAttendance";
            if(this.newAttendance.type==="上班"){
                  this.logItem.opn = "上班打卡";
              }else if(this.newAttendance.type==="下班"){
                this.logItem.opn = "下班打卡";
              }
            this.logItem.res = "false";
            addLog(this.logItem);
            this.$message.error('考勤失败');  
            console.error(error);  
          });  
      } else {  
        // 表单验证失败的处理  
        return false;  
      }  
    });  
  },  
  resetNewAttendance() {  
    this.newAttendance = {  
      type: '',  
      name: '',   
      notes: '' 
    };  
  },  
  handleCancelAdd() {  
    this.showAddModal = false;  
    this.resetNewAttendance();  
  },
  getUsers(){
      getUserList().then((response) => {  
        console.log(response.data)
        this.userList = response.data;  
      });  
    },
    
    saveNewAttendanceStandard() {  
    this.$refs.newAttendanceStandardForm.validate((valid) => {  
      if (valid) {  
        addAttendanceStandard(this.newAttendanceStandard)  
          .then(response => {  
            console.log(this.newAttendanceStandard)
        this.$message.success('新考勤标准添加成功');  
        this.showAddStandardModal = false;  
        this.logItem.mn = "saveNewAttendanceStandard";
        if(this.newAttendanceStandard.type==="上班"){
              this.logItem.opn = "上班打卡标准";
          }else if(this.newAttendanceStandard.type==="下班"){
            this.logItem.opn = "下班打卡标准";
          }
        this.logItem.res = "true";
        addLog(this.logItem);
        this.resetNewAttendanceStandard(); }
          ).catch(error =>{
            this.$message.error('新标准添加失败');  
            this.logItem.mn = "saveNewAttendanceStandard";
            if(this.newAttendanceStandard.type==="上班"){
              this.logItem.opn = "上班打卡标准";
          }else if(this.newAttendanceStandard.type==="下班"){
            this.logItem.opn = "下班打卡标准";
          }
          this.logItem.res = "false";
          addLog(this.logItem);
            console.log(this.newAttendanceStandard)
            console.error(error);  
          }) 
      } else {  
        // 表单验证失败的处理  
        return false;  
      }  
    });  
  },  
  resetNewAttendanceStandard() {  
    this.newAttendanceStandard = {  
      type: '',  
      standardTime:''
    };  
  },  
  handleCancelAddStandard() {  
    this.showAddStandardModal = false;  
    this.resetNewAttendanceStandard();  
  },
  filterData() {
    this.currentPage = 1;
  }
  }
}
</script>

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;

}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
/deep/.el-table .cell {  
  color: black;
}  
.button{
  background: #788fd3;
  color: white;
}
.paging{
  margin: 0;
  padding: 0;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}
</style>